﻿using Ops.Host.Core.Models;

namespace Ops.Host.Core.Services.Impl;

internal sealed class CardInfoService : ICardInfoService
{
    private readonly IFreeSql _freeSql;

    public CardInfoService(IFreeSql freeSql) => _freeSql = freeSql;

    public bool Exist(string cardNo)
    {
        return _freeSql.Select<CardInfo>().Any(x => x.CardNo == cardNo);
    }

    public List<CardInfo> GetAll()
    {
        return _freeSql.Select<CardInfo>().ToList();
    }

    public async Task<(List<CardInfo> items, long count)> GetPagedAsync(CardInfoFilter filter, int pageIndex, int pageItems)
    {
        var items = await _freeSql.Select<CardInfo>()
                          .WhereIf(!string.IsNullOrEmpty(filter.CardNo), s => s.CardNo.Contains(filter.CardNo!))
                          .WhereIf(filter.PLevel != null, s => s.PLevel == filter.PLevel!)
                          .OrderBy(s => s.CreatedAt)
                          .Count(out var total) //总记录数量
                          .Page(pageIndex, pageItems)
                          .ToListAsync();
        return (items, total);
    }

    public void Enable(int id)
    {
        _freeSql.Update<CardInfo>(id)
            .Set(s => s.IsEnabled, true)
            .Set(s => s.UpdatedAt, DateTime.Now)
            .ExecuteAffrowsAsync();
    }

    public void Disable(int id)
    {
        _freeSql.Update<CardInfo>(id)
            .Set(s => s.IsEnabled, false)
            .Set(s => s.UpdatedAt, DateTime.Now)
            .ExecuteAffrowsAsync();
    }

    public async Task<CardInfo> AddCardInfoAsync(CardInfo model)
    {
        model.CreatedAt ??= DateTime.Now;

        var repo = _freeSql.GetRepository<CardInfo>();
        return await repo.InsertAsync(model);
    }

    public async Task UpdateCardInfoAsync(CardInfo model)
    {
        var repo = _freeSql.GetRepository<CardInfo>();
        var cardInfo = repo.Where(s => s.Id == model.Id).First();

        if (cardInfo != null)
        {
            cardInfo.PLevel = model.PLevel;
            cardInfo.Owner = model.Owner;
            cardInfo.Description = model.Description;
            cardInfo.IsEnabled = model.IsEnabled;
            cardInfo.UpdatedAt = DateTime.Now;

            await repo.UpdateAsync(cardInfo);
        }
    }

    public void DeleteCardInfo(int id)
    {
        _freeSql.Delete<CardInfo>(id).ExecuteAffrows();
    }
}
